package com.vanysoft.framework.config.mvc;

import com.vanysoft.business.sys.entity.UserInfo;
import com.vanysoft.framework.exception.VanySoftBaseException;
import com.vanysoft.framework.messagesource.MessageCodeConstant;
import com.vanysoft.framework.redis.RedisService;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

public class UserInfoArgumentsResolver implements HandlerMethodArgumentResolver {

    private final RedisService redisService;

    public UserInfoArgumentsResolver(RedisService redisService) {
        this.redisService = redisService;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(SessionUser.class) && parameter.getParameterType().equals(UserInfo.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        String token = webRequest.getParameter("token");
        if (StringUtils.isEmpty(token)) {
            throw new VanySoftBaseException(MessageCodeConstant.LoginConstant.LOGIN_TIME_OUT);
        }
        UserInfo userInfo = redisService.getUserInfo(token);
        if (null == userInfo) {
            throw new VanySoftBaseException(MessageCodeConstant.LoginConstant.LOGIN_TIME_OUT);
        }
        return userInfo;
    }
}